package com.starblink.android.charles

import okhttp3.Interceptor
import okhttp3.Response
import java.util.concurrent.TimeUnit

/**
 * 抓包拦截器
 * @note （1）仅测试环境可用（2）开关控制
 */
class PacketCaptureInterceptor() : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        val startNs = System.nanoTime()
        var response = chain.proceed(request)
        val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)

        if (CharlesManager.isPub?.invoke() == false && CharlesManager.isUploadPacketInfo()) {
//            SKLogger.e(TAG, "==========PacketCaptureSubstituteInterceptor=========")
//            SKLogger.e(TAG, "Request信息：")
//            SKLogger.e(TAG, "Request基本信息=${request}")
//            request.body?.let {
//                val buffer = Buffer()
//                it.writeTo(buffer)
//                SKLogger.e(TAG, "RequestBody=${buffer.readString(UTF_8)}")
//            }
//
//            SKLogger.e(TAG, "Response信息：")
//            SKLogger.e(TAG, "Response基本信息=${response}")
//            SKLogger.e(TAG, "ResponseHeader=${response.headers}")
//            response.body?.let {
//                val source = it.source()
//                source.request(Long.MAX_VALUE) // Buffer the entire body.
//                var buffer = source.buffer
//                SKLogger.e(TAG, "ResponseBody=${buffer.clone().readString(UTF_8)}")
//            }
            CharlesManager.uploadApiResponse(request, response, tookMs)
        }

        return response
    }

    companion object {
        const val TAG = "dss"
    }
}